<template>
  <!-- 列表 -->
  <section class="list">
    <!-- 头部筛选区域 -->
    <section class="top">
      <!-- <el-input
        v-model="tableParams.userName"
        clearables
        placeholder="搜索权限包"
      />
      <el-button icon="search" type="primary" @click="queryListFun"
        >查询</el-button
      > -->
      <!-- <el-button icon="DocumentAdd" @click="addOrEditPointFun('add')"
        >权限点管理</el-button
      > -->
      <el-button icon="DocumentAdd" type="success" @click="addOrEditFun('add')"
        >新增权限包</el-button
      >
    </section>
    <!-- 表格区域 -->
    <el-table :data="tableData" stripe class="content" v-loading="tableLoading">
      <el-table-column
        v-for="item in tableColumn"
        :key="item.prop"
        :prop="item.prop"
        :label="item.label"
        :width="item.width"
      />
      <el-table-column fixed="right" label="操作" width="200">
        <template #default="scope">
          <el-button
            link
            type="warning"
            size="small"
            @click="addOrEditFun('edit', scope.row)"
            >编辑</el-button
          >
          <el-button
            link
            type="danger"
            size="small"
            @click="deleteFun(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页区域 -->
    <section class="bottom">
      <el-pagination
        background
        v-model:current-page="tableParams.pageNum"
        v-model:page-size="tableParams.pageSize"
        :total="tableDataTotal"
        @size-change="changePageSize"
        @current-change="changePageNum"
      />
    </section>
  </section>
  <!-- 新增权限包侧弹框 -->
  <el-drawer v-model="drawer" title="新增权限包" size="50%">
    <el-form
      v-if="drawer"
      :model="form"
      label-width="120px"
      label-position="top"
      ref="formRef"
    >
      <el-form-item label="权限包名称">
        <el-input v-model="form.packageName" />
      </el-form-item>
      <!-- 管理系统 -->
      <el-form-item label="管理系统：">
        <Tree
          key="1"
          v-model:permission-ids="form.permissionIds"
          :option-type="optionType"
          :platform-id="1"
          :data-source="permissionPointList.management"
          :updateData="updateDataFun"
        />
      </el-form-item>
      <!-- H5系统 -->
      <el-form-item label="H5/小程序：">
        <Tree
          key="2"
          v-model:permission-ids="form.permissionIds"
          :option-type="optionType"
          :platform-id="2"
          :data-source="permissionPointList.h5"
          :updateData="updateDataFun"
        />
      </el-form-item>
      <!-- 地址系统 -->
      <el-form-item label="地址系统：">
        <Tree
          key="3"
          v-model:permission-ids="form.permissionIds"
          :option-type="optionType"
          :platform-id="3"
          :data-source="permissionPointList.address"
          :address-list="addressList"
          :updateData="updateDataFun"
        />
      </el-form-item>
      <!-- 课程系统 -->
      <el-form-item label="课程系统：">
        <Tree
          key="4 "
          v-model:permission-ids="form.permissionIds"
          :option-type="optionType"
          :platform-id="4"
          :data-source="permissionPointList.course"
          :course-list="courseList"
          :updateData="updateDataFun"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="closeDrawer">取消</el-button>
      <el-button type="primary" @click="addPermissionPackage"> 确定 </el-button>
    </template>
  </el-drawer>
</template>

<script setup>
import { ref } from "vue";
import { useRouter } from "vue-router";
import { storeToRefs } from "pinia";
import { userStore } from "@/stores/userInfo";
import { ElMessageBox } from "element-plus"; // 统一提醒
import {
  tableColumn,
  queryListRequest,
  deleteRequest,
  addPermissionPackageRequest,
  getPermissionPointListRequest,
  queryPermissionPackageDetailByPackageIdRequest,
} from "@/apis/permission.js";
import { queryListRequest as querryAddressListRequest } from "@/apis/address.js";
import { queryListRequest as querryCourseListRequest } from "@/apis/course.js";
import Tree from "./tree.vue";

const router = useRouter();
const userInfo = userStore();
/**表格相关**/
// 表格数据
let tableData = ref([]);
// 表格请求参数
let tableParams = ref({
  userName: "", //关键字
  pageNum: 1, // 页面
  pageSize: 10, // 条数
});
// 表格请求loading
let tableLoading = ref(false);
//表格总页数
let tableDataTotal = ref(0);
// 获取列表数据函数
const queryListFun = async () => {
  tableLoading.value = true;
  const res = await queryListRequest(tableParams.value);
  tableData.value = res.data;
  tableDataTotal.value = res.count;
  tableLoading.value = false;
};
// 初始化请求
queryListFun();
// 更改页码
const changePageSize = (pageSize) => {
  tableParams.value.pageSize = pageSize;
  queryListFun();
};
// 更改页码
const changePageNum = (pageNum) => {
  tableParams.value.pageNum = pageNum;
  queryListFun();
};

/**新增政策弹框**/
const drawer = ref(false);
const formInit = () => {
  form.value.id = "";
  form.value.packageName = "";
  form.value.permissionIds = [];
};

const form = ref({
  id: "",
  packageName: "",
  permissionIds: [],
});

const addOrEditFun = async (type, rowData = {}) => {
  drawer.value = true;
  if (type == "edit") {
    form.value.id = rowData.id;
    form.value.packageName = rowData.packageName;

    const res = await queryPermissionPackageDetailByPackageIdRequest({
      id: rowData.id,
    });
    const getAllIds = (data) => {
      let ids = [];
      data.forEach((item) => {
        ids.push(item.id);
        if (item.children && item.children.length > 0) {
          ids = ids.concat(getAllIds(item.children));
        }
      });
      return ids;
    };
    form.value.permissionIds = [
      ...getAllIds(res.data.management || []),
      ...getAllIds(res.data.h5 || []),
      ...getAllIds(res.data.address || []),
      ...getAllIds(res.data.course || []),
    ];
    console.log(form.value.permissionIds);
  } else {
    formInit();
  }
};

const closeDrawer = () => {
  drawer.value = false;
  formInit();
};

/**新增权限包**/
const addPermissionPackage = async () => {
  const res = await addPermissionPackageRequest(form.value);
  if (res.code == "00000") {
    ElMessage.success("新增权限包成功");
    closeDrawer();
    queryListFun();
  }
};
/**获取权限点列表**/
let permissionPointList = ref([]);
const getPermissionPointList = async () => {
  const res = await getPermissionPointListRequest();
  permissionPointList.value = res.data;

  const transformData = (data) => {
    data.map((item) => {
      item.label = item.permissionName;
      if (item.children && item.children.length > 0) {
        transformData(item.children);
      }
    });
  };
  transformData(permissionPointList.value.management || []);
  transformData(permissionPointList.value.h5 || []);
  transformData(permissionPointList.value.address || []);
  transformData(permissionPointList.value.course || []);
};

/**删除权限包**/
const deleteFun = async (params) => {
  ElMessageBox.confirm("确定删除该权限包吗？", "Warning", {
    title: "",
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        instance.confirmButtonLoading = true;
        instance.confirmButtonText = "删除中...";
        await deleteRequest({ id: params });
        queryListFun();
        done();
        setTimeout(() => {
          instance.confirmButtonLoading = false;
        }, 300);
      } else {
        done();
      }
    },
  });
};

/**获取地址列表**/
let addressList = ref([]);
const getAddressList = async () => {
  addressList.value = [];
  const res = await querryAddressListRequest({
    pageNum: 1,
    pageSize: 1000,
  });
  res.data.forEach((item) => {
    if (!permissionPointList.value.address.find((x) => x.dataId == item.id)) {
      addressList.value.push({
        id: item.id,
        addressName: item.addressName,
      });
    }
  });
};

/**获取课程列表**/
let courseList = ref([]);
const getCourseList = async () => {
  courseList.value = [];
  const res = await querryCourseListRequest({
    pageNum: 1,
    pageSize: 1000,
  });
  res.data.forEach((item) => {
    if (!permissionPointList.value.course.find((x) => x.dataId == item.id)) {
      courseList.value.push({
        id: item.id,
        courseName: item.courseName,
      });
    }
  });
};

/**更新数据**/
const updateDataFun = async () => {
  await getPermissionPointList();
  await getAddressList();
  await getCourseList();
};

updateDataFun();
</script>
<style lang="less" scoped>
.list {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
  .top {
    display: flex;
    .el-input {
      width: 300px;
      margin-right: 20px;
    }
  }
  .content {
    width: 100%;
    flex: 1;
    overflow-y: hidden;
    margin-top: 20px;
    margin-bottom: 20px;
  }
  .bottom {
    display: flex;
    flex-direction: row-reverse;
  }
}
</style>
